#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>

#define MAXMSZ   512

struct mymsg {
    long type;
    char text[MAXMSZ];
};


static void err_sys(const char* str) {
    fprintf(stderr, "%s: %s\n", str, strerror(errno));
    exit(1);
}

int main(int argc, char *argv[]) {
    key_t key;
    long qid;
    size_t nbytes;
    struct mymsg m;

    if (argc != 3) {
        fprintf(stderr, "usage: sendmsg KEY, message. (two parameter)\n");
        exit(1);
    }

    // 将参数argv[1]转换为10进制key
    key = strtol(argv[1], NULL, 0);

    if ((qid = msgget(key, 0)) < 0) {
        err_sys("can't open queue key");
    }

    memset(&m, 0, sizeof (m));

    strncpy(m.text, argv[2], MAXMSZ - 1);
    nbytes = strlen(m.text);
    m.type = 1;

    if (msgsnd(qid, &m, nbytes, 0) < 0) {
        err_sys("can't send message");
    }

    return 0;
}
